/*************************************************************************
	> File Name: 006.折半查找-数组.c
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 三  8/25 11:28:52 2021
 ************************************************************************/

#include <stdio.h>

//arr数组中查找 x 是否存在，数组长度为n，若找到了则返回x所在数组下标，否则返回-1

int binary_search(int *arr, int x, int n) {
    int head = 0, tail = n - 1, mid;
    while (head <= tail) {
        mid = (head + tail) / 2;
        if (arr[mid] == x) return mid;
        if (arr[mid] < x) head = mid + 1;
        else tail = mid - 1;
    }
    return -1;
}

int main() {
    int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    printf("%d\n", binary_search(arr, 4, 8));
    return 0;
}
